<script lang="ts">
	import { createEventDispatcher, onMount } from "svelte";
	import PaperAirplane from "$lib/assets/chat/svelte/PaperAirplane.svelte";
	import AddFile from "$lib/assets/chat/svelte/AddFile.svelte";
	import TagSelector from "./TagSelector.svelte";

	export let query: string = "";
	let loading: boolean = false;
	let selectedTags = { documentType: "", chartType: "" };
	const dispatch = createEventDispatcher();

	// 页面加载时添加事件监听
	onMount(() => {
		// 监听图片上传事件
		const handleImageUpload = (event: CustomEvent<{ imageText: string }>) => {
			const { imageText } = event.detail;
			// query += imageText; // 将 "@Image" 添加到输入框
		};

		window.addEventListener('imageUploaded', handleImageUpload as EventListener);

		return () => {
			// 组件销毁时移除事件监听器
			window.removeEventListener('imageUploaded', handleImageUpload as EventListener);
		};
	});

	// 处理消息发送
	function handleTextSubmit() {
		if (!query.trim() || loading) return;
		let finalQuery = query;
		// prompt for the Mermaid code
		// finalQuery = `Please generate the Mermaid code for the ${selectedTags.chartType} in the ${selectedTags.documentType} based on the description below: ${query}`;
        finalQuery = `请生成  ${selectedTags.documentType} 中的 ${selectedTags.chartType} 的Mermaid代码，图片中要表示的内容如下: ${query}`;
		dispatch("submit", {query,finalQuery});
	}

	// 处理键盘按下事件，支持 Enter 发送消息
	function handleKeydown(event: KeyboardEvent) {
		if (event.key === "Enter") {
			event.preventDefault();
			handleTextSubmit();
		}
	}

	// 更新选中的标签
	function updateTags(event: {
		detail: { documentType: string; chartType: string };
	}) {
		selectedTags = event.detail;
	}
</script>

<div class="border-t p-4">
	<TagSelector on:update={updateTags} bind:selectedTags />

	<div class="mt-2 flex items-center">
		<input
			bind:value={query}
			type="text"
			class="flex-1 rounded-lg border p-2 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
			placeholder="Type a message..."
			on:keydown={handleKeydown}
		/>
		<!-- <button
			class="ml-2 rounded-lg bg-gray-100 p-2 text-white transition duration-200 hover:bg-gray-200 active:bg-gray-300"
			on:click={handleTextSubmit}
			disabled={loading}
		>
			<AddFile />
		</button> -->
		<AddFile />
		<button
			class="send-button ml-2 rounded-lg  p-2 text-white transition duration-200  active:bg-blue-700"
			on:click={handleTextSubmit}
			disabled={loading}
		>
			<PaperAirplane />
		</button>
	</div>
</div>

<style>
.send-button{
	background-color: #876899;
}

.send-button:hover{
	background-color: #705E78;
}

.send-button:active{
	background-color: #705E78;
}
</style>